const esbuild = require("esbuild");
const axios = require("axios");

const MyPlugin = {
  name: "http-url",
  setup(build) {
    // onStart
    // onResolve
    build.onResolve({ filter: /^https?:\/\// }, (args) => {
      return {
        namespace: "http-url",
        path: args.path,
      };
    });

    build.onResolve({ filter: /.*/, namespace: "http-url" }, (args) => {
      console.log(args.path, args.importer);
      return {
        namespace: "http-url",
        path: new URL(args.path, args.importer).toString(),
      };
    });

    // onLoad
    build.onLoad({ filter: /.*/, namespace: "http-url" }, async (args) => {
      const { data } = await axios(args.path);
      return {
        contents: data,
      };
    });
    // onEnd
  },
};

esbuild.build({
  entryPoints: ["app.js"],
  bundle: true,
  outfile: "out.js",
  plugins: [MyPlugin],
});
